package com.ych.modules.api.authorInfc.fileAuth.service.impl;

import com.ych.SDK.alibaba.ossSDK.AliOssUtil;
import com.ych.SDK.alibaba.ossSDK.config.AliOssConfig;
import com.ych.modules.api.authorInfc.fileAuth.service.IFileService;
import com.ych.utils.UUID;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Author: Usopp.tsui
 * Date: 2021/3/11
 * Time: 13:50
 * Description:
 */
@Service("IFileService")
public class FileServiceImpl implements IFileService {
    @Autowired
    private              AliOssUtil       aliOssUtil;
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    @Override
    public String uploadFile(MultipartFile file, String userId) {
        try {
            String path;
            if (null == file || null == file.getInputStream()) {
                throw new RuntimeException("文件为空");
            }
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));//后缀名
            String newFileName = UUID.randomUUID() + suffix; //重新用uuid命名
            if (StringUtils.isBlank(userId)) {
                path = AliOssConfig.path + "/public/" + sdf.format(new Date()) + "/" + newFileName;
            } else {
                path = AliOssConfig.path + "/private/" + userId + "/" + sdf.format(new Date()) + "/" + newFileName;
            }
            aliOssUtil.fileUpload(path, file.getInputStream());//上传文件
            return aliOssUtil.getOssObjectDownAuthUrl(path);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
